<?php
/**
 * @Author: liuhongbin
 * @Email: 514660094@qq.com
 * @Date: 2019-02-12 16:15:10
 * @Description:
 * @LastEditors: liuhongbin
 * @LastEditTime: xxx
 */

namespace app\controller\work;

use app\common\model\platform\Platform;
use hiduoke\services\workWechat\WorkWechatOpen;
use hiduoke\services\WorkWechatService;
use think\App;
use app\common\controller\WechatController;
use think\facade\Cache;

class Oauth extends WechatController
{
    public function __construct(App $app)
    {
        parent::__construct($app);
    }
    // 用户授权
    public function callBack()
    {
        $code = input('code');
        $auth = (new Platform())->where(['plaid' => get_plaid()])->value('auth_type');//授权模式
        if ($auth == 0 && get_plaid()) {
            // 自建应用
            $user = (new WorkWechatService())->getAppsApp()->oauth->detailed()->userFromCode($code);
            $userDetail = $user->getRaw();
        } else {
            //  服务商
            $app = (new WorkWechatOpen())->getOpenApp();
            $user = $app->corp->getUserByCode($code);
            if ($user['errcode'] == 0) {
                // TODO 这里可能站长未将用户添加到应用可见范围，导致无法获取用户信息
                if(empty($user['user_ticket'])){
                    return showMessage('用户无权限,请检查是否在应用可见范围，请重试！', 'error', '', -1, ['show_btn' => false]);
                }
                $userDetail = $app->corp->getUserByTicket($user['user_ticket']);
            } else {
                Cache::set($this->getKey('work_wx_user'), $user);
            }
        }
        Cache::set($this->getKey('work_wx_user'), $userDetail);
        $target_url = Cache::get($this->getKey('target_url'));
        if (!$target_url) {
            return showMessage('授权出现错误，请重试！', 'error', '', -1, ['show_btn' => false]);
        }
        if (strpos($target_url, '&wxref=mp.weixin.qq.com')) {
            $target_url = str_replace('&wxref=mp.weixin.qq.com', '', $target_url) . '&wxref=mp.weixin.qq.com#wechat_redirect';
        } else {
            $target_url .= '&wxref=mp.weixin.qq.com#wechat_redirect';
        }
        to($target_url);
        return '';
    }

    protected function getKey($string)
    {
        return $string . input('sid') . '_' . input('p');
    }
}
